package cn.Liujialin.basic.service.impl;

import cn.Liujialin.basic.constant.BaseConstant;
import cn.Liujialin.basic.service.IVerifyCodeService;
import cn.Liujialin.basic.stant.BeanContant;
import cn.Liujialin.basic.util.StrUtils;
import cn.Liujialin.cation.BusinessException;
import cn.Liujialin.user.domain.User;
import cn.Liujialin.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    @Transactional
    public void smsCode(Map<String,String> param ) {
        String phone = param.get("phone");
        String type = param.get("type");
// 校验 手机号不能为空
        //扫描微信登录之后要加一个是否验证type为空
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(type)) {
            throw new BusinessException("请输入正确的信息");
        }

        //微信扫码登录
        //定义一个字符串
        String businessKey="";

        if(type.equals("register")){
            //注册验证码
            //        手机号不能被注册 查询user表
            User userTmp = userMapper.findByPhone(phone);
            if(userTmp != null){
                throw new BusinessException("用户已注册，请登录");
            }
            businessKey = BaseConstant.BUSINESS_TYPE_REGISTER + phone;
        }else if(type.equals("binder")){
            //微信绑定验证码
            businessKey = BaseConstant.BUSINESS_TYPE_BINDER + phone;
        }
        sendCode(businessKey);

    }





    //抽取公共代码
    public void sendCode(String businessKey){
        //验证码是否有效  拼接key从redis查询出验证码
        //BeanContant.BUSINESS_TYPE_REGISTER + phone被抽公共代码了
        Object codeTmp = redisTemplate.opsForValue().get(businessKey);
// 判断验证码是否有效  value有值                   v
        String code = "";
        if (codeTmp != null) {
//查询到了，有效(还没有过3分钟)，还需要判断是否过了重发时间
            String timeStr = codeTmp.toString().split(":")[1];
            if (System.currentTimeMillis() - Long.valueOf(timeStr) <= 1 * 60 * 1000) {
                throw new BusinessException("请勿重复,点击发送");
            }
//如果过了，用原来的验证码
            code = codeTmp.toString().split(":")[0];
        } else {
//没有查询到，验证码失效直接生成新的验证码
            code = StrUtils.getComplexRandomString(6);
        }
// 处理业务将code保存到redis并设置3分钟过期
        redisTemplate.opsForValue().set(
                //BeanContant.BUSINESS_TYPE_REGISTER + phone = businessKey 被抽公共代码了
                businessKey,
                code + ":" + System.currentTimeMillis(),
                5,
                TimeUnit.MINUTES);

        System.out.println(code + ",请在5分钟内使用！");


    }

}
